#include "threadPool.h"
int getChildDirId(const char* dir, MYSQL *conn, const char *username) {
  int child_dir_id;
  char sql_query[512] = {0};
  snprintf(sql_query, sizeof(sql_query),
           "SELECT id FROM fileSystem WHERE filename = '%s' AND username = '%s' AND type = 'd'",
           dir, username);
  if (0 != mysql_query(conn, sql_query)) {  // 查询错误
    fprintf(stderr, "getChildDirId() query failed: %s\n",
            mysql_error(conn));
    return -1;
  } else {
    MYSQL_RES *result = mysql_store_result(conn);
    if (NULL == result) {  // 未返回结果集 内存分配失败 连接中断
      fprintf(stderr, "getChildDirId() store result failed: %s\n",
              mysql_error(conn));
      return -1;
    }
    MYSQL_ROW row = mysql_fetch_row(result);
    if (NULL == row) {
      if (0 != mysql_error(conn)) {  // 读取行过程中发生错误
        fprintf(stderr, "getChildDirId() fetch row failed: %s\n",
                mysql_error(conn));
        return -1;
      }
    }
    char *endptr;
    errno = 0;
    child_dir_id = (int)strtol(row[0], &endptr, 10);
    if (errno != 0 || *endptr != '\0') {  // 转换失败
      fprintf(stderr, "getChildDirId() cast failed: %s\n", row[0]);
      return -1;
    }
    mysql_free_result(result);
  }
  printf("getChildDirId() successful: child_dir_id = %d\n", child_dir_id);
  return child_dir_id;
}

bool isDirEmpty(const char* dir, MYSQL *conn, const char *username) {
  bool empty = true;
  char sql_query[512] = {0};
  snprintf(sql_query, sizeof(sql_query),
           "SELECT * FROM fileSystem WHERE username = '%s' AND parent_id = %d AND type = 'd'",
           username, getChildDirId(dir, conn, username));
  if (0 != mysql_query(conn, sql_query)) {  // 查询错误
    fprintf(stderr, "isDirEmpty() query failed: %s\n",
            mysql_error(conn));
  } else {
    MYSQL_RES *result = mysql_store_result(conn);
    if (NULL != result) {  // 返回了结果集
      if (0 != mysql_num_rows(result)) {  // 结果集不为空 不是空目录
        empty = false;
        printf("isDirEmpty() dir not empty\n");
        mysql_free_result(result);
      }  // 结果集为空 是空目录
    } else {  // 未返回结果集 内存分配失败 连接中断
      fprintf(stderr, "isDirEmpty() store result failed: %s\n",
              mysql_error(conn));
    }
  }
  return empty;
}

int rmdirFunc(dirStack_t *pwd, const char *dirs, char *error_msg,
    MYSQL *conn, const char* username) {
  bool fail = false;
  char fail_msg[4096] = {0};
  int offset = 0;
  int cur_dir_id = pwd->top->data;
  char *token, *saveptr;
  char *dirs_dup = strdup(dirs);
  token = strtok_r(dirs_dup, " ", &saveptr);
  while (token != NULL) {
    char sql_query[512] = {0};
    snprintf(sql_query, sizeof(sql_query),
             "SELECT * FROM fileSystem WHERE filename = '%s' AND username = '%s' AND parent_id = %d AND type = 'd' LIMIT 1",
             token, username, cur_dir_id);
    if (true == isQueryResultExist(conn, sql_query)) {   // 有此目录
      if (false == isDirEmpty(token, conn, username)) {  // 该目录不为空 不能rmdir
        offset += snprintf(fail_msg + offset, sizeof(fail_msg) - offset,
                         "[ERROR]: directory \"%s\" is not empty\n", token);
        fail = true;
      } else {  // 该目录为空 可以rmdir
        memset(sql_query, 0, sizeof(sql_query));
        snprintf(sql_query, sizeof(sql_query),
                 "DELETE FROM fileSystem WHERE filename = '%s' AND username = '%s' AND parent_id = %d AND type = 'd'",
                 token, username, cur_dir_id);
        if (0 != mysql_query(conn, sql_query)) {  // 删除错误
          fprintf(stderr, "rmdirFunc() query failed: %s\n",
                  mysql_error(conn));
        } else {
          printf("rmdirFunc() delete successful: sql_query = %s\n", sql_query);
        }
      }
    } else {  // 无此目录
      offset += snprintf(fail_msg + offset, sizeof(fail_msg) - offset,
                         "[ERROR]: No such directory like \"%s\"\n", token);
      fail = true;
    }
    token = strtok_r(NULL, " ", &saveptr);
  }
  free(dirs_dup);
  return fail ? -1 : 0;
}

